package com.lin.service.impl;

import cn.hutool.core.io.resource.ClassPathResource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.lin.dto.CarUserBillDTO;
import com.lin.entity.CarUserBill;
import com.lin.entity.User;
import com.lin.entity.UserBalance;
import com.lin.entity.UserExtraCost;
import com.lin.mapper.CarUserBillMapper;
import com.lin.mapper.UserBalanceMapper;
import com.lin.mapper.UserMapper;
import com.lin.service.CarUserBillService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lin.service.EmailService;
import com.lin.util.AsposeUtil;
import com.lin.util.OrderSerialUtil;
import com.lin.vo.DataVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 林伟鸿
 * @since 2021-11-24
 */
@Service
public class CarUserBillServiceImpl extends ServiceImpl<CarUserBillMapper, CarUserBill> implements CarUserBillService {

    @Autowired
    CarUserBillMapper carUserBillMapper;

    @Autowired
    UserBalanceMapper userBalanceMapper;
    @Autowired
    private EmailService emailService;

    @Autowired
    UserMapper userMapper;

    QueryWrapper<CarUserBill> queryWrapper;
    IPage<CarUserBill> iPage;

    /**
     * 用户租车
     * @param carUserBillDTO 接受前端的DTO对象
     * @return
     */
    @Override
    public synchronized int rentalCar(CarUserBillDTO carUserBillDTO) {
        Integer carId = carUserBillDTO.getCarId();
        queryWrapper = new QueryWrapper<CarUserBill>().eq("car_id", carId);
        CarUserBill selectBill = carUserBillMapper.selectOne(queryWrapper);
        if (selectBill == null) {
            //实例化CarUserBill对象
            CarUserBill carUserBill = new CarUserBill();
            //通过BeanUtils赋值同名属性
            BeanUtils.copyProperties(carUserBillDTO, carUserBill);
            //运用订单编号工具类生成唯一订单编号
            carUserBill.setOrderSerial(OrderSerialUtil.createUniqueOrderSerial());
            Integer orderPrice = carUserBillDTO.getOrderPrice();
            UserBalance userBalance = userBalanceMapper.selectById(carUserBillDTO.getUserId());
            //用户余额扣款
            userBalance.setMoney(userBalance.getMoney() - orderPrice);
            userBalanceMapper.updateById(userBalance);
            return carUserBillMapper.insert(carUserBill);
        }else {
            return 2;
        }

    }

    @Override
    public DataVO<CarUserBill> carUserBillInformation(Integer page, Integer limit,String userId) {
        DataVO<CarUserBill> dataVO = new DataVO<>();
        dataVO.setMsg("");
        dataVO.setCode(0);
        iPage = new Page<>(page,limit);
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        IPage<CarUserBill> carUserBillIPage = carUserBillMapper.selectPage(iPage, queryWrapper);
        dataVO.setCount(carUserBillIPage.getTotal());
        dataVO.setData(carUserBillIPage.getRecords());
        return dataVO;
    }

    /**
     * 发送合同给用户
     * @param orderSerial 订单编号
     * @return 执行结果
     * @throws IOException
     */
    @Override
    public String sendContract(String orderSerial) throws IOException {
        //通过Mybatis-Plus的QueryWrapper对象
        queryWrapper = new QueryWrapper<>();
        //添加筛选条件，数据库中找出这个订单的记录
        queryWrapper.eq("order_serial", orderSerial);
        //获得carUserBill对象
        CarUserBill carUserBill = carUserBillMapper.selectOne(queryWrapper);
        //拿到用户Id，方便后续拿到邮箱
        Integer userId = carUserBill.getUserId();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        User user = userMapper.selectOne(wrapper);
        //拿到nickName
        String nickName = user.getNickName();
        //拿到订单金额
        Integer orderPrice = carUserBill.getOrderPrice();
        //拿到剩余时间
        Integer lastDay = carUserBill.getLastDay();
        //时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //时间的格式化
        Date createTime = carUserBill.getCreateTime();
        String date = sdf.format(createTime);

        //时间输出分割处理
        String[] split = date.split("-");
//        XWPFTemplate template = XWPFTemplate.compile("C:\\Users\\LinWeihong\\Desktop\\凤达汽车租赁合同.docx").render(
        ClassPathResource resource = new ClassPathResource("static\\contract\\凤达汽车租赁合同.docx");
        InputStream stream = resource.getStream();
        //字段填充
        XWPFTemplate template = XWPFTemplate.compile(stream).render(
                new HashMap<String, Object>(){{
                    put("nickName", nickName);
                    put("rentalPrice",orderPrice);
                    put("date", date);
                    put("year", split[0]);
                    put("month", split[1]);
                    put("day", split[2]);
                    put("lastDay", lastDay);
                }});
        //通过IO流处理文件
       
        template.writeAndClose(new FileOutputStream("src\\main\\resources\\static\\contract\\"+orderSerial+".docx"));
        AsposeUtil.wordToPdf("src\\main\\resources\\static\\contract\\"+orderSerial+".docx","src\\main\\resources\\static\\contract\\"+orderSerial+".pdf");
        emailService.sendAttachmentsMail(user.getEmail(), "凤达汽车租赁信息管理有限公司", "租车合同", "src\\main\\resources\\static\\contract\\"+orderSerial+".pdf");
        return "发送合同成功";
    }


    @Override
    public DataVO<CarUserBill> allCarUserBillsInformation(Integer page, Integer limit) {
        DataVO<CarUserBill> dataVO = new DataVO<>();
        dataVO.setMsg("");
        dataVO.setCode(0);
        iPage = new Page<>(page,limit);
        IPage<CarUserBill> carUserBillIPage = carUserBillMapper.selectPage(iPage, null);
        dataVO.setCount(carUserBillIPage.getTotal());
        dataVO.setData(carUserBillIPage.getRecords());
        return dataVO;
    }
}
